/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package queenb.net.util;

import org.apache.log4j.Logger;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

/**
 * Hibernate Utility class with a convenient method to get Session Factory
 * object.
 *
 * @author thanhct
 */
public class QueenbUtil {

    private static Logger logger = Logger.getLogger(QueenbUtil.class);
    private static final SessionFactory sessionFactory;
    //private static final SessionFactory sessionFactoryOracle;
    public static boolean DEBUG = true;

    public static void out(String output) {
        if (DEBUG) {
            System.out.println(output);
        }
    }

    public static void err(String error) {
        System.err.println(error);
    }

    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml)
            // config file.
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
            // sessionFactoryOracle = new AnnotationConfiguration().configure("hibernateoracle.cfg.xml").buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception.
            logger.debug("Initial SessionFactory creation failed." + ex.getMessage());
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static String showMode() {
        if (transactionActive()) {
            return sessionFactory.getCurrentSession().getFlushMode().toString();
        }
        return "NOT-ACTIVE";
    }

    public static void beginViewTransaction() {
        sessionFactory.getCurrentSession().beginTransaction();
        sessionFactory.getCurrentSession().setFlushMode(FlushMode.NEVER);
    }

    public static void beginWriteTransaction() {
        sessionFactory.getCurrentSession().beginTransaction();
        sessionFactory.getCurrentSession().setFlushMode(FlushMode.AUTO);
    }

    public static boolean transactionActive() {
        return sessionFactory.getCurrentSession().getTransaction().isActive();
    }

    public static void commitTransaction() throws HibernateException {
        if (transactionActive()) {
            sessionFactory.getCurrentSession().getTransaction().commit();
        }
    }

    public static void roolbackTransaction() {
        if (transactionActive()) {
            sessionFactory.getCurrentSession().getTransaction().rollback();
        }
    }
    /**
     * @return the sessionFactoryOracle
     */
    //public static SessionFactory getSessionFactoryOracle() {
    //    return sessionFactoryOracle;
    // }
}
